package com.mall.shopping.services;

import com.mall.shopping.IHomeService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContent;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.HomePageResponse;
import com.mall.shopping.dto.PanelDto;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @program: mall-parent
 * @description:
 * @author: zhijie
 * @create: 2021-12-13 17:00
 **/
@Service
public class HomeServiceImpl implements IHomeService {
    @Autowired
    PanelMapper panelMapper;
    @Autowired
    PanelContentMapper panelContentMapper;
    @Autowired
    ContentConverter contentConverter;

    @Override
    public HomePageResponse homepage() {
        HomePageResponse homePageResponse = new HomePageResponse();
        Example example = new Example(Panel.class);
        List<PanelDto> panelDtos = null;
        try {
            List<Panel> panels = panelMapper.selectByExample(example);
            if (panels.size() > 0) {
                for (Panel panel : panels) {
                    List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
                    panel.setPanelContentItems(panelContentItems);
                }
                panelDtos = contentConverter.panels2Dto(panels);
            }
        } catch (Exception e) {
            homePageResponse.setCode(ShoppingRetCode.SYSTEM_TIMEOUT.getCode());
            homePageResponse.setMsg(ShoppingRetCode.SYSTEM_TIMEOUT.getMessage());
            return homePageResponse;
        }
        homePageResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        homePageResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        if (panelDtos != null) {
            Set<PanelDto> collect = panelDtos.stream().collect(Collectors.toSet());
            homePageResponse.setPanelContentItemDtos(collect);
        }
        return homePageResponse;
    }
}
